package middleware

import (
	"cloud.hubbleye.appalert.service_r/internal/config"
	"cloud.hubbleye.appalert.service_r/internal/model"
	"encoding/json"
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/clients"
	"github.com/nacos-group/nacos-sdk-go/common/constant"
	"github.com/nacos-group/nacos-sdk-go/vo"
	"go.uber.org/zap"
)

func init() {
	ReadDbconfig()
}

var ThisNacosData model.NacosData

//监听nacos配置
func ReadDbconfig() {
	defer func() {
		if err := recover(); err != nil {
			strValue, ok := err.(string)
			if ok {
				Logger.Info("ReadDbconfig() function",
					zap.String("error_message->", strValue),
				)
			}
		}
	}()
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr: config.NacosPath,
			Port:   config.NacosPort,
		},
	}
	// 创建clientConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         "",
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogLevel:            "debug",
	}
	// 创建动态配置客户端的另一种方式 (推荐)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		Logger.Info("ReadDbconfig() clients.NewConfigClient  error",
			zap.String("error_message->", err.Error()),
		)
	}
	//获取配置信息
	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: "cloud.hubbleye.appalert.service",
		Group:  "DEFAULT_GROUP"})
	if err != nil {
		Logger.Info("ReadDbconfig() configClient.GetConfig  error",
			zap.String("error_message->", err.Error()),
		)
	}
	//解析数据库信息
	if err := json.Unmarshal([]byte(content), &ThisNacosData); err == nil {
		fmt.Println("NSQ的地址是", ThisNacosData.NSQ)
		fmt.Println("告警中心的url地址是", ThisNacosData.AlertCfgurls)
	} else {
		Logger.Info("ReadDbconfig() json.Unmarshal  error",
			zap.String("error_message->", err.Error()),
		)
	}
	//监听配置
	err = configClient.ListenConfig(vo.ConfigParam{
		DataId: "golang_template_project_nacos",
		Group:  "DEFAULT_GROUP",
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Println("group:" + group + ", dataId:" + dataId + ", data:" + data)
			if err := json.Unmarshal([]byte(data), &ThisNacosData); err == nil {
				//有变动
			} else {
				Logger.Info("ReadDbconfig() OnChange json.Unmarshal  error",
					zap.String("error_message->", err.Error()),
				)
			}
		},
	})
	if err != nil {
		Logger.Info("ReadDbconfig() configClient.ListenConfig  error",
			zap.String("error_message->", err.Error()),
		)
		return
	}
}
